package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUsermapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUsermapper, AdUser> implements AdUserService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDto dto) {
        //检查参数
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //根据用户名查询用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        //用户存在，检查密码是否正确
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!inputPwd.equals(user.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //检查用户状态是否正常，status=9
        if (user.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }
        //修改最近登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //生成token，封装返回结果{user: {用户信息}  ,  token: "令牌凭证" }

       // AppJwtUtil.getToken(user.getId().longValue());
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO adUserVO = new AdUserVO();
        //属性拷贝
        BeanUtils.copyProperties(user,adUserVO);
        //返回结果jwt
       Map result = new HashMap<>();
       result.put("user",adUserVO);
       result.put("token",token);
       return ResponseResult.okResult(result);
    }

    /*
    后端用户注册
    */
    @Override
    public ResponseResult register(AdUser user) {
        //参数校验
        if (StringUtils.isEmpty(user.getName())
                || StringUtils.isEmpty(user.getPassword())){
             CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名和密码不能为空");
        };
        //用户注册，存储用户名和密码加密信息
        //用户密码加密规则是：md5（密码+salt）
        String salt = RandomStringUtils.randomAlphanumeric(8);
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex((password+salt).getBytes()));
        user.setSalt(salt);
        user.setCreatedTime(new Date());
        user.setStatus(9);
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
